<template>
  <!-- 使用卡片布局 -->
  <el-card class="box-card">
    <template #header>修改密码</template>

    <!-- 表单 -->
    <el-form
      :model="passForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
      size="mini"
    >
      <el-form-item label="原密码" prop="oldPwd">
        <el-input
          type="text"
          v-model="passForm.oldPwd"
          autocomplete="off"
          @blur="checkOld"
        ></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input
          type="text"
          v-model="passForm.password"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="checkPwd">
        <el-input
          type="text"
          v-model="passForm.checkPwd"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >提交</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import {
  validatePass,
  validateNewPass,
  validateCheckPass
} from '@/utils/validate.js'

import { checkOldPass, editPass } from '@/api/users.js'
import local from '@/utils/local.js'

export default {
  data() {
    // 已知在这里写的验证函数访问this是没有问题的
    return {
      // 数据对象
      passForm: {
        oldPwd: '',
        password: '',
        checkPwd: ''
      },
      // 规则对象
      rules: {
        oldPwd: [{ validator: validatePass, trigger: 'blur' }],
        password: [{ validator: validateNewPass(this), trigger: 'blur' }],
        checkPwd: [{ validator: validateCheckPass(this), trigger: 'blur' }]
      },
      state: false
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          // 如果原密码验证错误不会发起请求
          if (!this.state) return this.$message.error('原密码错误！！')
          const { code } = await editPass({
            newPwd: this.passForm.password
          })
          // console.log(data)
          if (code === 0) {
            // 修改了密码之后，要重新登录
            local.cls()
            setTimeout(() => {
              // 刷新页面
              location.reload()
            }, 1500)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 检查原密码
    async checkOld() {
      const { code } = await checkOldPass({
        oldPwd: this.passForm.oldPwd
      })
      if (code === '00') {
        this.state = true
      } else {
        this.state = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 370px;

  .el-input {
    width: 178px;
  }
}
</style>
